package br.ufes.inf.lprm.cwtools.web;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class AndroidConfigurationParser {
	private AndroidConfigurationParser() {
		/* Prevents instantiation. */
	}
	
	public static Map<String, String> parse(InputStream source) {
		try {
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			AndroidConfigurationHandler handler = new AndroidConfigurationHandler();
			parser.parse(source, handler);
			return handler.getAndroidConfigurations();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	private static class AndroidConfigurationHandler extends DefaultHandler {
		private static final String COMPONENT_SETTING = "ComponentSetting";
		
		private Map<String, String> androidConfigs = null;
		
		public Map<String, String> getAndroidConfigurations() {
			return this.androidConfigs;
		}
		
		public AndroidConfigurationHandler() {
			androidConfigs = new HashMap<String, String>();
		}
		
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			
			if (qName.equalsIgnoreCase(COMPONENT_SETTING)) {
				String mKey = attributes.getValue("key");
				String mValue = attributes.getValue("value");
				this.androidConfigs.put(mKey, mValue);
			}
		}
	}
}